<template>
    <div class="common">
        <innerCommon 
            :location="location"
        >
            <div slot="left">
                <a-button icon="plus"  type="primary" @click="openAddQuestion()">添加题目</a-button>
                <a-button-group style="margin-left:10px;">
                    <a-button>
                        <a-checkbox :checked="checkedAll" @click="selectAllOuter()">全选</a-checkbox>
                    </a-button>
                    <a-button @click="deleteQuestion()">
                        <a-icon type="delete" />
                    </a-button>
                    <a-button @click="showAllAnswer()">
                        <a-icon type="arrows-alt" />{{showAnswerText}}
                    </a-button>
                    <download 
                        :name="'导出试卷'"
                        :api="'manage/paper/export'"
                        :fileName="info&&info.title+'.xls'"
                        :formData="{'paperId':paperId}"
                        :isPrimary="false"
                    ></download>
                </a-button-group>
                <a-button-group style="margin-left:10px;">
                    <a-button @click="previewPaper">
                        <a-icon type="copy" />试卷预览
                    </a-button>
                    <a-button @click="openReviewTitleBox">
                        <a-icon type="edit" />编辑标题
                    </a-button>
                </a-button-group>

            </div>
            <div slot="right">
                <a-button type="primary" @click="returnBack()">返回</a-button>
            </div>
            <div slot="table">
                <h2 v-if="info">{{info.title}}</h2>
                <div class="paperDetail">
                    <a-tag v-for="(item,index) in infoList" :key="index">{{item}}</a-tag>
                </div>
                <div class="paperContent">
                    <a-row>
                        <a-col :span="16">
                            <question
                                :subjectList="questionList"
                                :pagination="pagination"
                                @selectItem="selectItemOuter"
                                @showAnswer="showAnswer"
                                @deleteItem="deleteItem"
                                @editItem="editItem"
                            ></question>
                        </a-col>
                        <a-col :span="6">
                            <ul class="static">
                                <li>按题型统计</li>
                                <li v-for="(item,index) in staticList" :key="index">
                                    <span>{{item.type}} ： <a-tag color="#2db7f5">{{item.num}}</a-tag> 题</span>
                                    <span>每题 ：<a-input-number style="width:65px;" :step="0.5" v-model="item.score" :min="1" :max="10"/> 分</span>
                                </li>
                                <li>
                                    <span>总计：<a-tag color="#2db7f5">{{totalNum}}</a-tag>题</span>
                                    <span>总分：<a-tag color="#2db7f5">{{totalScore}}</a-tag>分</span>
                                </li>
                                <li>
                                    <span>及格分：<a-input-number style="width:65px;" v-if="info" v-model="info.passScore" :min="1" :max="totalScore"/> 分</span>
                                </li>
                                <li style="text-align:center"><a-button type="primary" @click="eidtScore()">确认修改</a-button></li>
                            </ul>
                        </a-col>
                    </a-row>
                </div>
            </div>
        </innerCommon>
        <!-- 添加题目 -->
        <a-modal
            class="addPaper"
            style="top: 20px;"
            width="1200px"
            :destroyOnClose='true'
            :visible="addQuestionModel"
            title="添加题目"
            okText='创建'
            cancelText="取消"
            @cancel="addQuestionModel=false"
            @ok="addQuestion()"
            >
                <div>
                    <div class="title" v-if="info">
                        <span>{{info.title}}</span>
                        <a-tag color="orange">{{info.majors[0].name}}</a-tag>
                        <a-tag color="green">{{info.majors[1].name}}</a-tag>
                    </div>
                    <div>
                        <a-row>
                            <a-col :span="8" style="padding:15px 15px 15px 0">
                                <div class="tableWrapper">
                                    <ul>
                                        <li>
                                            <span>序号</span>
                                            <span>题库名称</span>
                                        </li>
                                        <li 
                                            v-for="(item,index) in questionBank" 
                                            @click="changeBank(index,item.id)" 
                                            :key="index"
                                            :class="{'isActive':currentIndex==index}"
                                            >
                                            <span>{{index+1}}</span>
                                            <span>{{item.title}}</span>
                                        </li>
                                    </ul>
                                </div>
                            </a-col>
                            <a-col :span="16" class="border-style">
                                <div class="header-box">
                                    <a-button-group style="margin:0 30px;">
                                        <a-button @click="selectAll()"><a-checkbox :checked="selectAllBtn">全选</a-checkbox></a-button>
                                        <a-button icon='arrows-alt' @click="showAll">{{showBtnText}}</a-button>
                                    </a-button-group>
                                    <a-input-search
                                        placeholder="输入题目名称"
                                        style="width: 200px"
                                        @search="searchQuestion"
                                    />
                                </div>
                                <div class="question-content">
                                    <question
                                       :subjectList="currentList"
                                       :isAction='false'
                                       @selectItem="selectItem($event,false)"
                                    ></question>
                                </div>
                            </a-col>
                        </a-row>
                    </div>
                </div>
        </a-modal>
        <!-- 修改标题 -->
        <a-modal
            :destroyOnClose='true'
            :visible="reviewTitleBox"
            title="编辑标题"
            okText='确定'
            cancelText="取消"
            @cancel="reviewTitleBox=false"
            @ok="reviewTitle">
                <div>
                    <eform
                        :formData="formData"
                        :fields="fields"
                        v-if="fields"
                        ref="form"
                    >
                    </eform>
                </div>
        </a-modal>
        <!-- 弹框--修改题目 -->
        <questionTypeModal
            :question="questionInfo"
            :answer="answer"
            :type="type"
            @cancel="detailBox=false"
            :detailBox="detailBox"
            @selectAnswer="selectAnswer"
            @submitQuestion="submitQuestion"
        ></questionTypeModal>
    </div>
</template>
<script>
const columns=[
    {
        title: '序号',
        dataIndex: 'index',
        width:70
    },{
        title: '题库名称',
        dataIndex: 'title',
    }
]
import download from "@/components/common/download"
import question from "@/components/common/question"
import innerCommon from "@/components/common/innerCommon"
import eform from "@/components/common/form"
import questionTypeModal from "@/components/common/questionTypeModal"
import {testDetailApi,getQuestionItemApi,updateTestApi} from "@/request/api"
export default {
    name:'mytestEdit',
    components:{innerCommon,download,question,eform,questionTypeModal},
    computed:{
        totalScore:function(){
            let total=0
            this.staticList.forEach((item)=>{
                total+=item.num*item.score
            })
            return total
        },
        totalNum:function(){
            if(this.info){
                return this.info.singleNum+this.info.multiNum+this.info.judgeNum
            }else{
                return 0
            }
        },
        selectAllBtn:function(){
            if(this.currentList.length==0){
                return false
            }
            let isAll=true
            this.currentList.forEach(item=>{
                if(!item.isSelect){
                    isAll=false
                }
            })
            return isAll
        },
        checkedAll:function(){
            if(this.questionList.length==0){
                return false
            }
            let isAll=true
            this.questionList.forEach(item=>{
                if(!item.isSelect){
                    isAll=false
                }
            })
            return isAll
        }
    },
    created(){
        this.paperId=this.$route.query.id
        this.ExamOrTest=this.$route.query.type
        this.location=[{
            name:"教学课堂管理",
            path:''
        },{
            name:this.ExamOrTest==0?"我的考试":"我的测试",
            path:'/mytest'
        },{
            name:'修改',
            path:'/myTestEdit'
        }]
        this.init()
    },
    data(){
        let validatePaperName=(rule,value,callback)=>{
            if(value!==''&&value.trim().length === 0){
                callback(new Error('试卷标题不能全是空格'))
            }else{
                callback()
            }
        }
        const formData=[{
            label:"试卷标题",
            prop:"title",
            rules:[{required:true,message:'试卷标题不能为空'},{validator:validatePaperName}],
            placeholder:'请输入试卷标题'
        }]
        return{
            fields:null,
            validatePaperName,
            formData,
            columns,
            location:[],
            paperId:'',
            info:null,
            staticList:[],//侧边统计分数的信息
            infoList:[],//头部试卷信息
            questionList:[],
            pagination:{pageSize:10,total:10,current:1,onChange: page => {
                this.changePage(page)
            }},
            addQuestionModel:false,
            questionBank:[],
            currentList:[],
            currentIndex:0,
            selectQuestion:[],
            showBtnText:'展开',
            showAnswerText:'展开',
            currentlibId:null,
            updateData:{
                'question':[],
                'paper_type':1,
            },
            reviewTitleBox:false,
            questionId:null,
            addQuestionBox:false,
            questionInfo:{},
            answer:[],
            correct:'',
            type:'',
            optionList:['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'],
            detailBox:false,
            ExamOrTest:0,//0是考试1是测试
        }
    },
    methods:{
        init(){
            this.getToken(testDetailApi,{paperId:this.paperId},res=>{
                this.info=res.data
                let info=res.data
                this.questionList=info.question.map(item=>({...item,'isSelect':false}))
                this.pagination.total=this.questionList.length
                this.infoList=[
                    '总分'+info.totalScore,
                    '及格分'+info.passScore,
                    '共'+this.totalNum+'题',
                    info.majors[0].name,
                    info.majors[1].name,
                    '创建时间'+info.createTime
                ],
                this.staticList=[
                    {
                        type:'单选题',
                        num:info.singleNum,
                        score:info.perSingle
                    },{
                        type:'多选题',
                        num:info.multiNum,
                        score:info.perMulti
                    },{
                        type:'判断题',
                        num:info.judgeNum,
                        score:info.perJudge
                    }
                ]
            })
        },
        // 修改题目
        selectItemOuter(index){
            if(this.questionList[index+parseInt(this.pagination.current-1)*10].isSelect){
                this.questionList[index+parseInt(this.pagination.current-1)*10].isSelect=false
            }else{
                this.questionList[index+parseInt(this.pagination.current-1)*10].isSelect=true
            }
        },
        selectAllOuter(){
            if(this.checkedAll){
                this.questionList=this.questionList.map(item=>({...item,'isSelect':false}))
            }else{
                this.questionList=this.questionList.map(item=>({...item,'isSelect':true}))
            }
        },
        deleteQuestion(){
            let arr=this.questionList.filter(item=>item.isSelect)
            if(arr.length==0){
                this.$message.error('请选择您要删除的题目')
                return
            }else{
                this.$confirm({
                    title: '确认删除吗?',
                    cancelText:"取消",
                    okText:'确定',
                    onOk:()=>{
                        this.updateData.question=this.questionList.filter(item=>!item.isSelect)
                        this.updateInfo()
                    },
                    onCancel() {
                    },
                });
            }
        },
        showAnswer(index){
            let target = this.questionList.filter(item=>item.id == index)[0]
            if(target.isShowAnswer){
                target.isShowAnswer=false
            }else{
                target.isShowAnswer=true
            }
        },
        showAllAnswer(){
            if(this.showAnswerText=='展开'){
                this.questionList=this.questionList.map(item=>({...item,isShowAnswer:true}))
                this.showAnswerText='收起'
            }else{
                this.questionList=this.questionList.map(item=>({...item,isShowAnswer:false}))
                this.showAnswerText='展开'
            }
        },
        deleteItem(data){
            this.$confirm({
                title:'确认删除该题目吗?',
                okText:'确认',
                cancelText:'取消',
                onOk:()=>{
                    this.updateData.question=this.questionList.filter(item=>item.id!=data)
                    this.updateInfo()
                },
                onCancel() {},
            })
        },
        previewPaper(){
            let routeData = this.$router.resolve({
                path: "/paperPreview",
                query: {id:this.paperId}
            });
            let width=800
            let left=parseInt((screen.availWidth/2) - (width/2))
            window.open(routeData.href, '_blank',"height=800, width="+width+", toolbar=no, menubar=no, scrollbars=no, resizable=no, location=no, status=no,top=50,left="+left);
        },
        openReviewTitleBox(){
            this.reviewTitleBox = true
            this.fields={'title':this.info.title}
        },
        reviewTitle(){
            this.$refs.form.form.validateFields().then(data=>{
                this.updateData.title=data.title
                this.updateInfo('editTitle')
            })  
        },
        eidtScore(){
            this.updateData={
                'perSingle':this.staticList[0].score,
                'perMulti':this.staticList[1].score,
                'perJudge':this.staticList[2].score,
                'passScore':this.info.passScore,
                'totalScore':this.totalScore
            }
            this.updateInfo()
        },
        editItem(item){
            if(item.type==3){
                this.$router.push({path:'/questionAction',query:{'item':JSON.stringify(item),'type':this.ExamOrTest,'paperId':this.paperId,'question':JSON.stringify(this.questionList)}})
                return
            }
            this.questionId=item.id
            switch(item.type){
                case 0:this.type='单选题'
                break;
                case 1:this.type='多选题'
                break;
                case 2:this.type='判断题'
                break;
            }
            this.questionInfo={'stem':item.title,'analyse':item.analyse}
            let arr=[]
            if(item.type==0){
                item.option.split('&&').forEach((element,index)=>{
                    arr.push({'itemDetails':element,'isSelect':this.optionList[index]==item.answer})
                })
                this.correct=item.answer
                this.answer=arr
            }else if(item.type==1){
                item.option.split('&&').forEach((element,index)=>{
                    arr.push({'itemDetails':element,'isSelect':item.answer.split('').indexOf(this.optionList[index])==-1?false:true})
                })
                this.correct=item.answer
                this.answer=arr
            }else{
                this.answer=item.answer
            }
            this.detailBox=true;
        },
        selectAnswer(data){
            if(this.type=='判断题'){
                this.answer=data
            }else{
                this.correct=data
            }
        },
        // 确认
        submitQuestion(questionInfo,data,type,answer){
            this.questionList.forEach(item=>{
                if(item.id==this.questionId){
                    item.title=questionInfo.stem
                    item.answer=type==2?this.answer:answer.join('')
                    item.option=data
                    item.type=type
                }
            })
            this.updateData.question=this.questionList
            this.updateInfo('detailBox')
        },
        // 添加题目
        openAddQuestion(){
            this.addQuestionModel=true
            this.getToken(getQuestionItemApi,{'majorId':this.info.majors[0].id},res=>{
                this.questionBank=res.data.map(item=>({
                    ...item,
                    'questions':item.questions.map(value=>({
                        ...value,
                        'isSelect':false,
                        'isShowAnswer':false
                    })
                )}))
                this.changeBank(0,this.questionBank[0].id)
            })
        },
        changeBank(index,id){
            this.currentIndex=index
            this.currentlibId=id
            this.currentList=this.questionBank[index].questions
            this.currentList=this.currentList.filter(item=>(this.questionList.filter(value=>value.id==item.id).length==0))
        },
        selectItem(index,all,arrow){
            if(all){
                this.currentList[index].isSelect=arrow
            }else{
                if(this.currentList[index].isSelect){
                    this.currentList[index].isSelect=false
                }else{
                    this.currentList[index].isSelect=true
                }
            }
        },
        selectAll(){
            let arrow=!this.selectAllBtn
            this.currentList.forEach((item,index)=>{
                this.selectItem(index,true,arrow)
            })
        },
        showAll(){
            if(this.currentList.filter(item=>item.isShowAnswer==false).length!=0){
                this.currentList.map(item=>item.isShowAnswer=true)
                this.showBtnText='收起'
            }else{
                this.currentList.map(item=>item.isShowAnswer=false)
                this.showBtnText='展开'
            }
        },
        searchQuestion(data){
            this.currentList=this.questionBank[this.currentIndex].questions.filter(item=>(item.title.indexOf(data)!=-1)).filter(item=>(this.questionList.filter(value=>value.id==item.id).length==0))
        },
        addQuestion(){
            let arr=[]
            this.questionBank.forEach(item=>{
                arr.push(item.questions.filter(item=>item.isSelect))
            })
            arr=arr.reduce((prev,next)=>{
                return [...prev,...next]
            })
            this.updateData.question=[...this.questionList,...arr]
            this.updateInfo('addModel')
        },
        updateInfo(type){
            this.getToken(updateTestApi,{...this.updateData,'paperId':this.paperId},res=>{
                this.$message.success(res.message)
                switch (type) {
                    case 'addModel' : this.addQuestionModel=false
                    break;
                    case 'editTitle' : this.reviewTitleBox=false
                    break;
                    case 'detailBox' : this.detailBox=false
                    break;
                }
                this.init()
            })
        },
        changePage(data){
            this.pagination.current=data
        },
        returnBack(){
            this.$router.go(-1)
        }
    }
}
</script>
<style lang="stylus" scoped>
.paperContent
    padding-top:20px;
    .static
        list-style:none;
        li
            line-height:40px;
            border:1px solid #ddd;
            border-top:0;
            padding:5px 20px;
            &:nth-child(1)
                border-top:1px solid #ddd;
                font-weight:bold;
                text-align:center;
            span 
                &:nth-child(1)
                    display inline
                    margin-right:30px;
.addPaper
    .title
        display:flex;
        align-items: center;
        border-bottom:1px solid #ddd;
        padding-bottom:30px;
        span
            font-size:16px;
            font-weight:bold;
            margin-right:20px;
    .tableWrapper
        ul
            list-style:none;
            border-bottom:1px solid #ddd;
            border-left:1px solid #ddd;
            padding:0;
            li
                line-height:40px;
                width:100%;
                display:flex;
                cursor pointer
                &:hover
                    background:#E6F7FF;
                &:nth-child(1)
                    background:#FAFAFA;
                span
                    cursor pointer
                    border-top:1px solid #ddd;
                    border-right:1px solid #ddd;
                    display:inline-block;
                    padding:0 10px;
                    line-height:40px;
                    &:nth-child(1)
                        width:20%
                    &:nth-child(2)
                        width:80%
            li.isActive
                background:#E6F7FF;

</style>